package com.hcy.app.screen.relax

import android.graphics.Paint
import android.text.TextPaint
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.unit.Dp

class TextPager(
    private val text: String,
    private val textPaint: TextPaint,
    private val maxWidth: Int,      // 使用 DP 单位
    private val maxLines: Int // 最大行

) {
    private var currentPageStart = 0
    private var _currentPage by mutableStateOf(0)
    private var _totalPages by mutableStateOf(0)
    private val pages = mutableListOf<String>()

    // 公共状态
    val currentPage: Int get() = _currentPage
    val totalPages: Int get() = _totalPages
    val currentPageText: String get() = pages.getOrNull(currentPage) ?: ""

    init {
        calculatePages()
    }

    private fun calculatePages() {
        pages.clear()
        currentPageStart = 0

        // 计算最大行数（基于高度和行高）
//        val maxLines = calculateMaxLines()

        while (currentPageStart < text.length) {
            val pageEnd = findPageEnd(
                text = text,
                start = currentPageStart,
                paint = textPaint,
                maxLines = maxLines,
                maxWidth = maxWidth
            )

            pages.add(text.substring(currentPageStart, pageEnd))
            currentPageStart = pageEnd
        }

        _totalPages = pages.size
        _currentPage = 0
    }

//    private fun calculateMaxLines(): Int {
//        // 计算单行高度（文本高度 + 行间距）
//        val lineHeightPx = textPaint.fontMetrics.let {
//            it.descent - it.ascent + lineSpacing.value * LocalDensity.current.density
//        }
//
//        // 计算最大行数
//        return (maxHeight.value * LocalDensity.current.density / lineHeightPx).toInt()
//    }

    fun goToNextPage() {
        if (_currentPage < _totalPages - 1) {
            _currentPage++
        }
    }

    fun goToPreviousPage() {
        if (_currentPage > 0) {
            _currentPage--
        }
    }

    fun goToPage(page: Int) {
        if (page in 0 until _totalPages) {
            _currentPage = page
        }
    }

    private fun findPageEnd(
        text: String,
        start: Int,
        paint: Paint,
        maxLines: Int,
        maxWidth: Int
    ): Int {
        var lineCount = 0
        var currentPosition = start
        var lineStart = start
        var pageEnd = start

        // 将 DP 转换为像素
//        val maxWidthPx = (maxWidth.value * LocalDensity.current.density).roundToInt()

        while (lineCount < maxLines && currentPosition < text.length) {
            // 查找下一个换行符或段落分隔符
            val nextNewLine = text.indexOf('\n', currentPosition)
            val paragraphEnd = if (nextNewLine == -1) text.length else nextNewLine + 1

            // 测量段落宽度
            val paragraph = text.substring(lineStart, paragraphEnd)
            val paragraphWidth = paint.measureText(paragraph)

            if (paragraphWidth <= maxWidth) {
                // 整段可以放在一行
                currentPosition = paragraphEnd
                pageEnd = paragraphEnd
                lineCount++
                lineStart = paragraphEnd
            } else {
                // 需要将段落分行
                val breakPosition = findLineBreakPosition(
                    text = text,
                    start = lineStart,
                    end = paragraphEnd,
                    paint = paint,
                    maxWidth = maxWidth
                )

                if (breakPosition == -1 || breakPosition <= lineStart) {
                    // 无法找到合适的分行位置，强制换行
                    currentPosition = paragraphEnd
                    pageEnd = paragraphEnd
                    lineCount++
                    lineStart = paragraphEnd
                } else {
                    currentPosition = breakPosition
                    pageEnd = breakPosition
                    lineCount++
                    lineStart = breakPosition

                    // 跳过换行符
                    if (currentPosition < text.length && text[currentPosition] == '\n') {
                        currentPosition++
                        lineStart = currentPosition
                    }
                }
            }

            // 检查是否到达文件末尾
            if (currentPosition >= text.length) {
                break
            }
        }

        return pageEnd
    }

    private fun findLineBreakPosition(
        text: String,
        start: Int,
        end: Int,
        paint: Paint,
        maxWidth: Int
    ): Int {
        var low = start + 1
        var high = end
        var breakPosition = -1

        // 二分查找最佳分行位置
        while (low <= high) {
            val mid = (low + high) / 2
            val testText = text.substring(start, mid)
            val testWidth = paint.measureText(testText)

            if (testWidth <= maxWidth) {
                // 可以容纳更多文本
                breakPosition = mid
                low = mid + 1
            } else {
                // 超出宽度，减少文本
                high = mid - 1
            }
        }

        // 如果找不到完美分行位置，尝试在单词边界处分割
        if (breakPosition == -1 || breakPosition <= start) {
            return findWordBoundary(text, start, end, maxWidth, paint)
        }

        return breakPosition
    }

    private fun findWordBoundary(
        text: String,
        start: Int,
        end: Int,
        maxWidth: Int,
        paint: Paint
    ): Int {
        // 从末尾向前查找最近的单词边界
        var position = minOf(end, start + maxWidth * 2) // 限制搜索范围

        while (position > start) {
            // 检查是否为单词边界（空格、标点等）
            if (isWordBoundary(text[position - 1], text[position])) {
                val testText = text.substring(start, position)
                if (paint.measureText(testText) <= maxWidth) {
                    return position
                }
            }
            position--
        }

        // 找不到单词边界，在maxWidth处强制分割
        for (i in start + 1 until end) {
            val testText = text.substring(start, i)
            if (paint.measureText(testText) > maxWidth) {
                return maxOf(start + 1, i - 1)
            }
        }

        return end
    }

    private fun isWordBoundary(charBefore: Char, charAfter: Char): Boolean {
        // 单词边界判断：空格、标点符号等
        return when {
            charAfter == '\n' -> true
            charBefore.isLetterOrDigit() && !charAfter.isLetterOrDigit() -> true
            !charBefore.isLetterOrDigit() && charAfter.isLetterOrDigit() -> true
            else -> false
        }
    }
}